using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace ColorBox4Sitecore.RessourcesRegistation
{
    public static class RessourceRegistrator
    {
        public static List<Ressource> RessourcesAlreadyRegistered
        {
            get
            {
                List<Ressource> ressourcesAlreadyRegistered;
                if (HttpContext.Current.Items["Colorbox4Sitecore_RessourcesHeaderRegistered"] != null)
                    ressourcesAlreadyRegistered = (List<Ressource>)HttpContext.Current.Items["Colorbox4Sitecore_RessourcesHeaderRegistered"];
                else
                    HttpContext.Current.Items["Colorbox4Sitecore_RessourcesHeaderRegistered"] = ressourcesAlreadyRegistered = ressourcesAlreadyRegistered = new List<Ressource>();

                return ressourcesAlreadyRegistered;
            }

            set { HttpContext.Current.Items["Colorbox4Sitecore_RessourcesHeaderRegistered"] = value; }
        }

        public static void RegisterRessources(Page page, List<Ressource> ressources)
        {
            foreach (Ressource res in ressources)
            {
                RegisterRessource(page, res);
            }
        }

        private static void RegisterRessource(Page page, Ressource res)
        {
            RessourceComparer comparer = new RessourceComparer();

            if (!RessourcesAlreadyRegistered.Contains(res, comparer))
            {
                if (res.Type == RessourceType.Js)
                {
                    HtmlGenericControl script = new HtmlGenericControl("script");
                    script.Attributes.Add("type", "text/javascript");
                    script.Attributes.Add("src", res.Path);
                    page.Header.Controls.Add(script);
                }
                else if (res.Type == RessourceType.Css)
                {
                    HtmlGenericControl link = new HtmlGenericControl("link");
                    link.Attributes.Add("type", "text/css");
                    link.Attributes.Add("href", res.Path);
                    link.Attributes.Add("rel", "stylesheet");
                    page.Header.Controls.Add(link);
                }

                RessourcesAlreadyRegistered.Add(res);
            }
        }
    }
}